package cn.dm.example.count;

import cn.dm.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class CountExample4 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    /*
     * 注:使用volatile关键字计数时,不是线程安全的
     * (总结：volatile不适用于计数的场景，但适用于共享变量的场景)
     */
    public static volatile int count = 0;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count);
    }

    private static void add() {
        count++;
        /**
         * count++分为三步
         * 1. 取count
         * 2. +1
         * 3. 写count
         *
         * 线程不安全原因：同一时刻有两个线程均取到了count(比如当前count=1000),然后进行+1操作,
         * 两个线程均为1001,然后再写count为1001,这就导致了不安全
         * (若是线程安全的话,此时预期1002才对)
         */
    }
}
